import type { App } from "vue";
import { defineComponent, defineAsyncComponent, h } from 'vue';

type SVGComponentMap = Record<string, ReturnType<typeof defineAsyncComponent>>;

interface SVGComponent {
  content: string;
  name: string;
}


async function getSVGComponents(): Promise<SVGComponentMap> {
  const svgModuleGlobs = import.meta.glob('@/assets/icons/**/*.svg');
  const svgComponents: SVGComponentMap = {};

  for (const [filePath, componentPromise] of Object.entries(svgModuleGlobs)) {
    const response = await fetch(filePath);
    const componentContext = await response.text();
    // 提取文件名作为组件名    
    const componentName = filePath.replace(/\/src\/assets\/icons\/(.*)\.svg/, '$1'); 
    //const componentName2 = filePath.replace(/\/src\/assets\/icons\/([^/]*)\/(.*)\.svg/, '$1-$2'); 
    // 定义异步组件，使用SVG内容
    svgComponents[componentName] = createSVGComponent(componentContext);
  }

  return svgComponents;
}

function createSVGComponent(svgContent:string): ReturnType<typeof defineComponent> {
    return {
      render() {
        return h('svg', { innerHTML: svgContent });
      },
    };
  }

export async function registerSVGIcons(app: App) {
  const svgComponents = await getSVGComponents();

  // 注册SVG组件
  for (const [name, component] of Object.entries(svgComponents)) {
    console.log("icon-"+name);
    app.component("icon-"+name, component);
  }
}

